<template>
  <div v-loading="loading">
    <el-card class="box-card knowledgeDetails">
      <div class="dflex">
        <div class="base-icon">
          <img :src="knowledgeIcon" alt="" srcset="" />
        </div>
        <div class="knowledge_title">
          <div class="f16333">
            <span>{{ d.knowledgeData.name }}</span>
            <span v-if="!!d.knowledgeUpdataList?.length" class="prompt"> {{ d.knowledgeUpdataList?.length }}文件</span>
          </div>
          <div class="f12999">{{ d.knowledgeData.info || "" }}</div>
        </div>
      </div>
    </el-card>
    <el-card class="box-card knowledgeUpdata">
      <div class="addFiles">
        <div>文件</div>
        <el-button v-if="d.knowledgeUpdataList.length" @click="dialogVisible = true" type="danger">
          + 添加文件
        </el-button>
      </div>

      <!-- 上传列表 -->
      <div v-if="d.knowledgeUpdataList.length" class="defaultTable">
        <el-table :data="d.knowledgeUpdataList" style="width: 100%">
          <el-table-column prop="filename" label="名称" width="300">
            <template #default="{ row }">
              <div class="download" @click="download(row.file, row.filename)">
                {{ row.filename }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="size" label="大小">
            <template #default="scope"> {{ scope.row.size }} kb </template>
          </el-table-column>
          <el-table-column prop="createtime" label="上传时间" width="300" />
          <el-table-column align="right" label="操作">
            <template #default="scope">
              <div class="dflex justify-content-end">
                <div class="base-del">
                  <img @click="onDel(scope.row.id)" :src="del" alt="" srcset="" />
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- end -->

      <!-- 无列表显示 -->
      <div class="knowledgeApp" v-if="!d.knowledgeUpdataList.length">
        <div>
          <img :src="NOF" alt="" srcset="" />
        </div>
        <p class="f14999">尚未添加文件</p>
        <el-button @click="dialogVisible = true" type="danger"> + 添加文件 </el-button>
      </div>

      <!-- 添加弹窗 -->
      <el-dialog
        style="border-radius: 10px"
        v-if="dialogVisible"
        v-model="dialogVisible"
        title="添加文件"
        width="600px"
      >
        <!-- @vue-ignore -->
        <el-upload
          :limit="1"
          class="upload-demo"
          drag
          action="#"
          :http-request="handleFileUpload"
          :before-upload="beforeUpload"
          accept=".pdf, .doc, .docx , image/jpg, image/jpeg, image/png"
          multiple
        >
          <!-- <el-icon class="el-icon--upload"><upload-filled /></el-icon> -->
          <img class="updataImg" :src="updata" alt="" srcset="" />
          <div class="el-upload__text">点击或拖动文件到此处上传</div>
          <template #tip>
            <div class="el-upload__tip">请上传 PNG、JPG、JPEG、PDF、DOC、DOCX 格式的文件。</div>
          </template>
        </el-upload>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button :loading="btLoading" type="danger" @click="completeUpload"> 完成 </el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import knowledgeIcon from "@/assets/docs/base_1.svg"
import NOF from "@/assets/docs/noF.svg"
import updata from "@/assets/docs/updata.svg"
import { reactive, ref } from "vue"
// import { UploadFilled } from '@element-plus/icons-vue'
import { apiFileDelete, apiKnowledgeFileGet, apiKnowledgeGet, apiUp_file } from "@/api/interface"
import del from "@/assets/docs/del.svg"
import debounce from "@/utils/debounce"
import download from "@/utils/download"
import dayjs from "dayjs"
import { ElMessage, ElMessageBox } from "element-plus"

const btLoading = ref(false)
const dialogVisible = ref(false)
const loading = ref<boolean>(false)
const routeKnowledgeDetails = JSON.parse(history.state.params)
console.log(routeKnowledgeDetails, "routeKnowledgeDetails")

// 文件 init
const getKnowledgeUpdataList = async () => {
  const params = {
    knowledge_id: routeKnowledgeDetails.id as unknown as number,
    page: 1
  }
  const { data } = await apiKnowledgeFileGet(params)
  d.knowledgeUpdataList = data.list.map((e: any) => {
    e.createtime = dayjs.unix(e.createtime).format("YYYY-MM-DD  HH:mm:ss")
    return e
  })
}

// 信息 init
const getKnowledgeData = async () => {
  const params = {
    id: routeKnowledgeDetails.id as unknown as number
  }
  const { data } = await apiKnowledgeGet(params)
  d.knowledgeData = data
}

// 知识库文件==>init
const initKnowledgeDetails = async () => {
  loading.value = true
  await getKnowledgeUpdataList()
  await getKnowledgeData()
  console.log(d)

  loading.value = false
}
// init
initKnowledgeDetails()

// 格式检查
const beforeUpload = (file: any) => {
  const testmsg = file.name.substring(file.name.lastIndexOf(".") + 1)
  console.log(testmsg)
  const testmsgArr = ["jpg", "png", "pdf", "doc", "docx"]
  const extension = testmsgArr.includes(testmsg)
  if (!extension) {
    ElMessage({
      type: "info",
      message: "上传错误"
    })
  }
  return extension
}

const d = reactive<any>({
  knowledgeData: {}, //文件信息
  knowledgeUpdataList: [], //文件列表
  file: null
})

// 删除
const delFn = debounce(async (id: number) => {
  const { code } = await apiFileDelete({ id })
  if (code === 200) {
    const newList = d.knowledgeUpdataList.filter((e: { id: number }) => e.id !== id)
    d.knowledgeUpdataList = newList
  }
}, 300)

// 处理文件上传暂存
const handleFileUpload = (file: any) => {
  d.file = file.file
}

// 完成上传
const completeUpload = debounce(async () => {
  try {
    btLoading.value = true
    const form = {
      file: d?.file,
      id: routeKnowledgeDetails.id
    }
    const { code } = await apiUp_file(form)
    if (code === 200) {
      getKnowledgeUpdataList()
      dialogVisible.value = false
    }
  } catch (error) {
    console.error(error)
  } finally {
    btLoading.value = false
  }
}, 300)

const onDel = debounce((id: number) => {
  ElMessageBox.confirm("相关记忆体将永久删除，请谨慎操作！是否继续删除？", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    ElMessage({
      type: "success",
      message: "删除成功"
    })
    delFn(id)
  })
}, 300)
</script>
<style lang="scss" scoped>
.knowledgeDetails {
  margin-bottom: 20px;

  .knowledge_title {
    line-height: 20px;
  }

  .prompt {
    padding: 2px 10px 2px 10px;
    border-radius: 20px;
    gap: 10px;
    display: inline-block;
    background: #eee;
    color: #666;
    font-size: 12px;
    margin-left: 10px;
  }

  .base-icon {
    width: 40px;
    height: 40px;
    flex-shrink: 0;
    border-radius: 10px;
    background: var(--v3-sidebar-menu-hover-bg-color);
    text-align: center;
    line-height: 55px;
    margin-right: 10px;
  }
}

.knowledgeUpdata {
  height: calc(100vh - 230px);

  .knowledgeApp {
    text-align: center;
    margin-top: 12%;
  }

  .el-upload__text {
    font-size: 14px;
    font-weight: 500;
    color: var(--el-color-info);
  }

  .el-upload__tip {
    font-size: 12px;
    font-weight: 400;
    color: #999;
  }

  .updataImg {
    margin: 10px 0;
  }

  .addFiles {
    display: flex;
    justify-content: space-between;
    align-content: center;
  }

  .defaultTable {
    margin: 20px 0;
  }

  .download {
    cursor: pointer;
  }
}
</style>
